package com.xing.order.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.wxpay.sdk.WXPayUtil;

import com.xing.order.entity.TOrder;
import com.xing.order.entity.TPayLog;
import com.xing.order.mapper.TPayLogMapper;
import com.xing.order.service.TOrderService;
import com.xing.order.service.TPayLogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.xing.order.utils.HttpClient;
import com.xing.servicebase.exceptionhandler.GuliException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 支付日志表 服务实现类
 * </p>
 *
 * @author xingfuao
 * @since 2022-04-08
 */
@Service
public class TPayLogServiceImpl extends ServiceImpl<TPayLogMapper, TPayLog> implements TPayLogService {

    @Autowired
    private TOrderService tOrderService;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;


    /**
     * 生成微信支付二维码
     *
     * @param orderNo
     * @return
     */

    @Override
    public Map createNative(String orderNo) {

//        String s1 = redisTemplate.opsForValue().get(orderNo);
//        if (s1 != null) {
//        }

        try {
            //1.根据订单号查询订单信息
            QueryWrapper<TOrder> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("order_no", orderNo);
            TOrder order = tOrderService.getOne(queryWrapper);

            //2.使用map设置生成二维码需要的参数
            //这样的map,不特意指定值，key可以使任何类型的
            Map map = new HashMap<>();
            map.put("appid", "wx74862e0dfcf69954");
            map.put("mch_id", "1558950191");
            map.put("nonce_str", WXPayUtil.generateNonceStr());
            map.put("body", order.getCourseTitle());
            map.put("out_trade_no", orderNo);
            map.put("total_fee", order.getTotalFee().
                    multiply(new BigDecimal("100")).longValue() + "");
            map.put("spbill_create_ip", "172.0.0.1");
            map.put("notify_url", "http://guli.shop/api/order/weixinPay/weixinNotify\n");
            map.put("trade_type", "NATIVE");

            //3.发送HttpClient请求，传递参数
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
            client.setXmlParam(WXPayUtil.generateSignedXml(map, "T6m9iK73b0kn9g5v426MKfHQH7X8rKwb"));
            client.setHttps(true);
            //执行发送请求
            client.post();

            //4.得到发送请求返回结果
            //返回的内容是xml格式
            String xml = client.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);

            //封装返回结果集合
            Map m = new HashMap<>();
            m.put("out_trade_no", orderNo);
            m.put("course_id", order.getCourseId());
            m.put("total_fee", order.getTotalFee());
            String result_code = resultMap.get("result_code");
            System.out.println("result_code===>" + result_code);
            String code_url = resultMap.get("code_url");
            System.out.println("code_url===>" + code_url);

            m.put("result_code", result_code); //返回二维码状态吗
            m.put("code_url", code_url);//二维码地址

            //微信支付二维码超过2小时自动过期。可采用2小时未支付取消订单
            redisTemplate.opsForValue().set(orderNo, String.valueOf(m), 120, TimeUnit.MINUTES);
            return m;
        } catch (Exception e) {
            e.printStackTrace();
            throw new GuliException(20001, "获取二维码失败");
        }
    }

    //根据订单号查询订单支付状态
    @Override
    public Map<String, String> queryPayStatus(String orderNo) {
        try {

            //1.封装参数
            Map m = new HashMap<>();
            m.put("appid", "wx74862e0dfcf69954");
            m.put("mch_id", "1558950191");
            m.put("out_trade_no", orderNo);
            m.put("nonce_str", WXPayUtil.generateNonceStr());

            //2.发送httpClient请求
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
            client.setHttps(true);
            //通过商户key加密
            client.setXmlParam(WXPayUtil.generateSignedXml(m, "T6m9iK73b0kn9g5v426MKfHQH7X8rKwb"));
            client.post();

            //3.返回第三方的数据
            String xml = client.getContent();
            //4.转成Map
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);

            //5.返回
            return resultMap;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 添加记录到支付表里面，并更新订单表的状态
     *
     * @param map
     */
    @Override
    public void updateOrderStatus(Map<String, String> map) {
        //获取前一步生成二维码的订单号
        String oradeNo = map.get("out_trade_no");
        //根据订单号，查询订单信息
        QueryWrapper<TOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("order_no", oradeNo);
        TOrder tOrder = tOrderService.getOne(wrapper);

        //判断订单状态是否为1，为1就是支付过了
        if (tOrder.getStatus().intValue() == 1) {
            return;
        }

        //更新订单表中的订单状态
        tOrder.setStatus(1);//代表已经支付
        tOrderService.updateById(tOrder);

        //向支付表里添加支付记录
        TPayLog tPayLog = new TPayLog();
        tPayLog.setOrderNo(oradeNo);//支付订单号
        tPayLog.setPayTime(new Date());//支付时间
        tPayLog.setPayType(1);//支付类型
        tPayLog.setTotalFee(tOrder.getTotalFee());//总金额
        tPayLog.setTradeState(map.get("trade_state"));//支付状态
        tPayLog.setTransactionId(map.get("transaction_id"));//订单流水号
        tPayLog.setAttr(JSONObject.toJSONString(map));
        baseMapper.insert(tPayLog);
    }


}
